/**
 * 测试1297指令 - 查看基础装备描述
 * 功能：测试装备详情查询功能
 */

const WebSocket = require('ws');

// WebSocket连接配置
const wsConfig = {
    url: 'ws://localhost:3000',
    timeout: 10000 // 10秒超时
};

class EquipmentDetailTester {
    constructor() {
        this.ws = null;
        this.isConnected = false;
        this.messageId = 0;
    }

    // 建立WebSocket连接
    async connect() {
        return new Promise((resolve, reject) => {
            try {
                console.log('🔌 正在连接WebSocket服务器...');

                this.ws = new WebSocket(wsConfig.url);

                this.ws.on('open', () => {
                    console.log('✅ WebSocket连接成功');
                    this.isConnected = true;
                    resolve();
                });

                this.ws.on('error', (error) => {
                    console.error('❌ WebSocket连接失败:', error.message);
                    reject(error);
                });

                this.ws.on('close', () => {
                    console.log('🔌 WebSocket连接已关闭');
                    this.isConnected = false;
                });

                this.ws.on('message', (data) => {
                    try {
                        const message = JSON.parse(data.toString());
                        this.handleMessage(message);
                    } catch (error) {
                        console.error('❌ 解析消息失败:', error.message);
                    }
                });

            } catch (error) {
                reject(error);
            }
        });
    }

    // 处理接收到的消息
    handleMessage(message) {
        console.log('📨 接收到消息:', JSON.stringify(message, null, 2));

        if (message.act_id === 1297) {
            if (message.code === 0) {
                console.log('✅ 1297指令执行成功');
                console.log('📋 装备详情数据:');
                if (message.data && Array.isArray(message.data)) {
                    message.data.forEach(item => {
                        console.log(`   ${item.k} ${item.v}`);
                    });
                }
            } else {
                console.log('❌ 1297指令执行失败:', message.msg);
            }
        }
    }

    // 发送WebSocket消息
    sendMessage(command, data = {}) {
        if (!this.isConnected) {
            throw new Error('WebSocket未连接');
        }

        const message = {
            c: command,
            d: data
        };

        console.log('📤 发送消息:', JSON.stringify(message, null, 2));
        this.ws.send(JSON.stringify(message));
    }

    // 测试1297指令 - 查看装备描述
    async testEquipmentDetail(equipmentId) {
        try {
            console.log(`\n🎯 测试1297指令 - 查看装备ID ${equipmentId} 的描述`);

            // 发送1297指令
            this.sendMessage(1297, { id: equipmentId });

            // 等待响应
            await this.waitForResponse(1297);

        } catch (error) {
            console.error('❌ 测试1297指令失败:', error.message);
        }
    }

    // 等待特定指令的响应
    waitForResponse(actId, timeout = wsConfig.timeout) {
        return new Promise((resolve, reject) => {
            const startTime = Date.now();

            const checkResponse = () => {
                if (Date.now() - startTime > timeout) {
                    reject(new Error(`等待 ${actId} 响应超时`));
                    return;
                }

                // 这里简化处理，实际应该监听特定消息
                setTimeout(() => {
                    resolve();
                }, 1000);
            };

            checkResponse();
        });
    }

    // 关闭连接
    close() {
        if (this.ws) {
            this.ws.close();
        }
    }

    // 运行测试
    async runTest() {
        console.log('🚀 开始测试1297指令 - 查看基础装备描述');
        console.log('='.repeat(50));

        try {
            // 1. 连接WebSocket
            await this.connect();

            // 2. 测试不同的装备ID
            const testEquipmentIds = [155, 132, 142, 152, 2, 3, 7]; // 包括头盔、武器等不同类型的装备

            for (const equipmentId of testEquipmentIds) {
                await this.testEquipmentDetail(equipmentId);
                await new Promise(resolve => setTimeout(resolve, 1000)); // 等待1秒
            }

            console.log('\n🎉 1297指令测试完成！');

        } catch (error) {
            console.error('💥 测试过程中发生错误:', error.message);
        } finally {
            // 3. 关闭连接
            this.close();
        }
    }
}

// 运行测试
async function main() {
    console.log('🎯 1297指令测试脚本');
    console.log('   功能：测试查看基础装备描述功能\n');

    const tester = new EquipmentDetailTester();
    await tester.runTest();
}

// 如果直接运行此脚本
if (require.main === module) {
    main().catch((error) => {
        console.error('💥 测试脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = EquipmentDetailTester;
